package com.lee.auth.security.context;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 用于对账号手机号加密并且和用户id合并
 *
 * @author lee HN
 * @date 2021/4/13 10:22
 */
public final class IdentityUtil {

    private static final String SEPARATOR = " ";

    private static final byte MOVE = 17;

    public static IdAccount split(String identity) {
        IdAccount idAccount;
        if (StringUtils.hasLength(identity)) {
            byte[] bytes = Base64Utils.decode(identity.getBytes(UTF_8));
            for (int i = 0; i < bytes.length; i++)
                bytes[i] = (byte) ~(bytes[i] - MOVE);
            String[] idAccounts = StringUtils.split(new String(bytes, UTF_8), SEPARATOR);
            if (idAccounts == null || idAccounts.length != 2) idAccount = null;
            else idAccount = new IdAccount(Long.parseLong(idAccounts[0]), idAccounts[1]);
        } else idAccount = null;
        return idAccount;
    }

    public static String join(Long id, String account) {
        byte[] bytes = (id + SEPARATOR + account).getBytes(UTF_8);
        for (int i = 0; i < bytes.length; i++)
            bytes[i] = (byte) (~bytes[i] + MOVE);
        return Base64Utils.encodeToString(bytes);
    }

    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    public static class IdAccount {

        public long id;

        public String account;

    }

}
